package com.cqh.recruit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqh.recruit.mapper.ActivityMapper;
import com.cqh.recruit.mapper.EmployeeMapper;
import com.cqh.recruit.mapper.StudentMapper;
import com.cqh.recruit.mapper.StuActMapper;
import com.cqh.recruit.pojo.entity.Activity;
import com.cqh.recruit.pojo.entity.Employee;
import com.cqh.recruit.pojo.entity.Student;
import com.cqh.recruit.pojo.entity.StuAct;
import com.cqh.recruit.service.IDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.Map;

/**
 * Dashboard 统计服务实现类
 *
 * @author dh
 * @since 2025-10-28
 * @version v1.0
 */
@Service
public class DashboardServiceImpl implements IDashboardService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private StuActMapper stuActMapper;

    @Override
    public Map<String, Object> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取总活动数
        Long totalActivities = activityMapper.selectCount(null);
        stats.put("totalActivities", totalActivities);
        
        // 获取学生总数
        Long totalStudents = studentMapper.selectCount(null);
        stats.put("totalStudents", totalStudents);
        
        // 获取员工总数
        Long totalEmployees = employeeMapper.selectCount(null);
        stats.put("totalEmployees", totalEmployees);
        
        // 获取报名总数
        Long totalEnrollments = stuActMapper.selectCount(null);
        stats.put("totalEnrollments", totalEnrollments);
        
        return stats;
    }

    @Override
    public Map<String, Object> getActivityStatusDistribution() {
        Map<String, Object> statusStats = new HashMap<>();
        
        // 统计各状态的活动数量
        // 状态：1-未开始，2-报名中，3-进行中，4-已结束，5-已取消
        QueryWrapper<Activity> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("status", 1);
        Long notStarted = activityMapper.selectCount(wrapper1);
        
        QueryWrapper<Activity> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("status", 2);
        Long enrolling = activityMapper.selectCount(wrapper2);
        
        QueryWrapper<Activity> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("status", 3);
        Long ongoing = activityMapper.selectCount(wrapper3);
        
        QueryWrapper<Activity> wrapper4 = new QueryWrapper<>();
        wrapper4.eq("status", 4);
        Long ended = activityMapper.selectCount(wrapper4);
        
        QueryWrapper<Activity> wrapper5 = new QueryWrapper<>();
        wrapper5.eq("status", 5);
        Long cancelled = activityMapper.selectCount(wrapper5);
        
        statusStats.put("notStarted", notStarted);
        statusStats.put("enrolling", enrolling);
        statusStats.put("ongoing", ongoing);
        statusStats.put("ended", ended);
        statusStats.put("cancelled", cancelled);
        
        return statusStats;
    }

    @Override
    public Map<String, Object> getMonthlyTrends() {
        Map<String, Object> trends = new HashMap<>();
        
        // 获取本月第一天和最后一天
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        
        // 本月新增活动
        QueryWrapper<Activity> activityWrapper = new QueryWrapper<>();
        activityWrapper.between("create_time", firstDayOfMonth, lastDayOfMonth);
        Long newActivities = activityMapper.selectCount(activityWrapper);
        
        // 本月新增学生
        QueryWrapper<Student> studentWrapper = new QueryWrapper<>();
        studentWrapper.between("create_time", firstDayOfMonth, lastDayOfMonth);
        Long newStudents = studentMapper.selectCount(studentWrapper);
        
        // 本月新增报名
        QueryWrapper<StuAct> enrollmentWrapper = new QueryWrapper<>();
        enrollmentWrapper.between("create_time", firstDayOfMonth, lastDayOfMonth);
        Long newEnrollments = stuActMapper.selectCount(enrollmentWrapper);
        
        // 计算增长率（这里简化处理，实际应该与上月对比）
        trends.put("newActivities", newActivities);
        trends.put("newStudents", newStudents);
        trends.put("newEnrollments", newEnrollments);
        
        // 简化的增长率计算（实际项目中应该与上月数据对比）
        trends.put("activityGrowthRate", calculateGrowthRate(newActivities));
        trends.put("studentGrowthRate", calculateGrowthRate(newStudents));
        trends.put("enrollmentGrowthRate", calculateGrowthRate(newEnrollments));
        
        return trends;
    }

    @Override
    public Map<String, Object> getEnrollmentStats() {
        Map<String, Object> enrollmentStats = new HashMap<>();
        
        // 获取总报名数
        Long totalEnrollments = stuActMapper.selectCount(null);
        enrollmentStats.put("totalEnrollments", totalEnrollments);
        
        // 获取本月报名数
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        
        QueryWrapper<StuAct> monthlyWrapper = new QueryWrapper<>();
        monthlyWrapper.between("create_time", firstDayOfMonth, lastDayOfMonth);
        Long monthlyEnrollments = stuActMapper.selectCount(monthlyWrapper);
        
        enrollmentStats.put("monthlyEnrollments", monthlyEnrollments);
        
        // 计算平均每个活动的报名人数
        Long totalActivities = activityMapper.selectCount(null);
        Double avgEnrollmentsPerActivity = totalActivities > 0 ? (double) totalEnrollments / totalActivities : 0.0;
        enrollmentStats.put("avgEnrollmentsPerActivity", Math.round(avgEnrollmentsPerActivity * 100.0) / 100.0);
        
        return enrollmentStats;
    }
    
    /**
     * 简化的增长率计算方法
     * 实际项目中应该与历史数据对比
     */
    private Double calculateGrowthRate(Long currentValue) {
        if (currentValue == null || currentValue == 0) {
            return 0.0;
        }
        // 这里简化处理，实际应该与上月数据对比
        // 假设一个基准值进行计算
        double baseValue = Math.max(1, currentValue * 0.8);
        return Math.round(((currentValue - baseValue) / baseValue) * 100 * 100.0) / 100.0;
    }
}
